<?php
/*
 * Created on June 3, 2010
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
?>
<?php
require_once APPPATH . "controllers/cmsbase.php";
class cms_product extends CmsBase {

	var $_require_login = true;
	var $upload_config = null;
	var $image_toolkit = null;
	var $mimes = null;

	function __construct() {		
		parent :: __construct();
		// Check permission
		parent::_check_permission('pms_product');
		$this->load->library('pagination');
		$this->load->model('Model_product', 'model_product');
		$this->load->model('Model_media', 'model_media');
		$this->load->helper('date');
		$this->load->helper('html');		
	}

	/**
	 * Name: index
	 * Param: pagination param
	 * Description:
	 *
	 */
	function index(){	
		$image_toolkit = $this->_settings['image_toolkit'];
		$this->image_toolkit = unserialize($image_toolkit);
		// Load pagination
		$this->javascript .= $this->_load_javascript("public/js/eye");
		$this->javascript .= $this->_load_javascript("public/js/utils");
		$this->javascript .= $this->_load_javascript("public/js/zoomimage");
		$this->css .= link_tag("public/css/zoomimage.css");
		
		// Load pagination
		$keyword = $this->input->post("keyword");
		$fromdate = $this->input->post("fromdate");
		$todate = $this->input->post("todate");
		$limit = 30;

		$offset = $this->uri->segment(3,0);

		$product_list = $this->model_product->browse($keyword, $fromdate, $todate, $limit, $offset);
		$count_list = $this->model_product->browse_count($keyword, $fromdate, $todate);

		$media_thumb = $this->config->item("media_thumb");

		$config['base_url'] = base_url()."admin.php/".$this->controller_name."/index/";
		$config['total_rows'] = $count_list;
		$config['per_page'] = $limit;

		$this->pagination->initialize($config);
		return $this->_render_my_view(array("product_list" => $product_list,
										"image_toolkit" => $this->image_toolkit,
										"media_thumb" => $media_thumb,
										"keyword" => $keyword,
										"fromdate" => $fromdate,
										"todate" => $todate));		
	}
	/**
	 *
	 *
	 */
	function add_product(){				
		$image_toolkit = $this->_settings['image_toolkit'];
		$this->image_toolkit = unserialize($image_toolkit);
		if (isset($_POST["PHPSESSID"])) {
			ini_set("html_errors", "0");
			// Load option from setting

			$config = $this->config->item("media_default");
			$config['max_size']	= $this->image_toolkit['max_size'];
			$config['max_width']  = $this->image_toolkit['large_width'];
			$config['max_height']  = $this->image_toolkit['large_height'];
			
			// Load library upload
			$this->load->library('upload', $config);
			if (!$this->upload->do_upload("Filedata"))
			{
				//$error = array('error' => $this->upload->display_errors());
				echo "ERROR:".$this->upload->display_errors();
			}
			else
			{
				// Get the image and create a thumbnail
				$data = $this->upload->data();
				$media = array('title' => $data['raw_name'],
								'filename' => $data['file_name'],
								'rawname' => $data['raw_name'],
								'fileext' => $data['file_ext'],
								'filetype' => $data['file_type'],
								'filesize' => $data['file_size'],
								'isimage' => $data['is_image']);

				$config = $this->config->item('media_thumb');
				$config['source_image'] = $data['full_path'];
				$config['width'] = $this->image_toolkit['thumb_width'];
				$config['height'] = $this->image_toolkit['thumb_height'];
				
				$this->load->library('image_lib', $config);
			
				if ( ! $this->image_lib->resize())
				{
				    echo  "ERROR:".$this->image_lib->display_errors();
					exit(0);
				}
				$this->image_lib->clear();
				$mediaId = $this->model_media->insert_media($media);				
				// Save to database
				$id = $this->model_product->insert_product(array('media_id' => $mediaId,'title' => $data['raw_name'],'price'=>$this->config->item('product_price')));
				echo "FILEID:".$id;
				exit(0);
			}
		}
		else{
			$this->javascript .= $this->_load_javascript("public/admin/js/swfupload/swfupload");
			$this->javascript .= $this->_load_javascript("public/js/handlers");
			$this->javascript .= $this->_load_javascript("public/js/fileprogress");
			$this->javascript .= $this->_load_javascript("public/js/swfupload.queue");
			$this->css .= link_tag("public/admin/css/swfupload.css");
			return $this->_render_my_view(array());
		}
	}
	/**
	 *
	 */
	function edit_product($id){
		$image_toolkit = $this->_settings['image_toolkit'];
		$this->image_toolkit = unserialize($image_toolkit);
		if(intval($id)){
			if($_SERVER['REQUEST_METHOD'] === 'POST')
			{
				// update Newsletter
				$data = parse_input('product_', $_POST);
				// Update group
				$this->model_product->update_product($id, $data);
				redirect(site_url(array('c' => 'cms_product', 'm' => 'index')));
			}
			else{
				$product = $this->model_product->find($id);
				$media_thumb = $this->config->item("media_thumb");
				return $this->_render_my_view(array("product" => $product, 'media_thumb' => $media_thumb));
			}
		}
	}
	
	/**
	 *
	 *
	 */
	function edit_multi_product(){		
		if($_SERVER['REQUEST_METHOD'] === 'POST')
		{
			$ids = $this->input->post('txtIds');
			$ids = trim($ids, ',');
			if(isset($_POST['btnSubmit'])){
				$ids = explode(',',$ids);
				$product_list = $this->model_product->find_by_ids($ids);
				$media_thumb = $this->config->item("media_thumb");
				return $this->_render_my_view(array('ids' => $ids, "product_list" => $product_list, 'media_thumb' => $media_thumb));
			}
			else{
				// update Newsletter
				$data_list = parse_input('product_', $_POST);
				if(isset($data_list['id'])){
					for($i = 0; $i < count($data_list['id']); $i++){
						$id = $data_list['id'][$i];
						$data = array('title' => $data_list['title'][$i],
							'keycode' => $data_list['keycode'][$i],
							'price' => $data_list['price'][$i],
							'description' => $data_list['description'][$i]);
						$this->model_product->update_product($id, $data);
					}
				}
				// Update group
				redirect(site_url(array('c' => 'cms_product', 'm' => 'index')));
			}
		}
	}
	
	/**
	 *
	 *
	 */
	function thumbnail($product_id){
		if ($product_id === false) {
			header("HTTP/1.1 500 Internal Server Error");
			echo "No ID";
			exit(0);
		}
		$product = $this->model_product->find($product_id);
		if (empty($product) || !intval($product['media_id'])) {
			header("HTTP/1.1 404 Not found");
			exit(0);
		}
		$media = $this->model_media->find($product['media_id']);
		
		$config = $this->config->item("media_thumb");
		$filepath = $config['upload_path'] . $media['rawname'] . $config['thumb_marker'] . $media['fileext'];
		$filetype = $media['filetype'];
		$fileext = strtolower(substr($media['fileext'], 1));
		$mime_type = $this->mimes_types($fileext);

		if(!empty($mime_type)){
			$filetype = is_array($mime_type) ? $mime_type[0] : $mime_type;
		}
		$size = getimagesize($filepath);
		//var_dump($size);exit;
		switch ($size[2])
	    {
	        case 1: $im = imagecreatefromgif($filepath); break;
	        case 2: $im = imagecreatefromjpeg($filepath); break;
	        case 3:				 
				$im = imagecreatefrompng($filepath);
				imagealphablending($im, false);
			    $colorTransparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
			    imagefill($im, 0, 0, $colorTransparent);
			    imagesavealpha($im, true); 
				break;
	        default: return '';  break;
	    }		
		/*header("Accept-Ranges: bytes");
		header("Expires:" . date('D, d M Y h:m:s'));*/
		header("Content-Length: " . filesize($filepath));
		header("Content-Type:" . $filetype);
	
		switch ($size[2])
	    {
	        case 1: imagegif($im); break;
	        case 2: imagejpeg($im);  break;
	        case 3: imagepng($im); break;
	        default: return '';  break;
	    }		
		imagedestroy($im);
		exit(0);
	}
	/**
	 *
	 *
	 */
	function delete_product($id){
		// Delete source image on hdd
		if ($id === false) {
			header("HTTP/1.1 500 Internal Server Error");
			echo "No ID";
			exit(0);
		}
		$product = $this->model_product->find($id);
		if (empty($product)) {
			header("HTTP/1.1 404 Not found");
			exit(0);
		}
		$config = $this->config->item("media_thumb");
		$filepath = $config['upload_path'] . $product['rawname'] . $config['thumb_marker'] . $product['fileext'];
		$filepath_thumb = $config['upload_path'] . $product['rawname'] . $product['fileext'];
		if(is_file($filepath)){
			unlink($filepath);
		}
		if(is_file($filepath_thumb)){
			unlink($filepath_thumb);
		}
		$this->model_media->delete_media($product['media_id']);
		$this->model_product->delete_product($id);
		//log_message("error", $this->db->last_query());
		$result = array('status' => 'success', 'message' => 'Deleted', 'product_id' => $id);
		echo json_encode($result);
		exit;
	}

	/**
	 * List of Mime Types
	 *
	 * This is a list of mime types.  We use it to validate
	 * the "allowed types" set by the developer
	 *
	 * @access	public
	 * @param	string
	 * @return	string
	 */
	function mimes_types($mime)
	{
		global $mimes;

		if (count($this->mimes) == 0)
		{
			if (@require_once(APPPATH.'config/mimes'.EXT))
			{
				$this->mimes = $mimes;
				unset($mimes);
			}
		}

		return ( ! isset($this->mimes[$mime])) ? FALSE : $this->mimes[$mime];
	}
	/**
	 *
	 *
	 */	
	function show_media(){
		$keyword = "";
		$fromdate = "";
		$todate = "";
		$limit = 10;

		$offset = $this->uri->segment(3,0);
		
		$img_list = $this->model_product->browse($keyword, $fromdate, $todate, $limit, $offset);
		$count_list = $this->model_product->browse_count($keyword, $fromdate, $todate);
		$media_thumb = $this->config->item("media_thumb");

		$config['base_url'] = base_url()."admin.php/".$this->controller_name."/show_media/";
		$config['total_rows'] = $count_list;
		$config['per_page'] = $limit;

		$this->pagination->initialize($config);
		return $this->load->view("cms_product/show_media",array("img_list" => $img_list, "media_thumb" => $media_thumb));
	}
}
